﻿

Public Class Guias

    Private oMaestra As New CMaestras
    Private oGuia As New CGuia
    Private dtItems As New DataTable
    Private dtOtrosCargos As New DataTable
    Private dtConceptos As New DataTable
    Private idItem As Integer
    Private idConcepto As Integer
    Private idGuia As Integer
    Private contadorItems As Integer
    Private contadorConceptos As Integer
    Public chargeableWeightCalculado As Double


    Private Sub Guias_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        'Oculta el panel de los filtros
        Me.Panel1.Size = New Size(Me.Panel1.Width, 15)
        Me.TabControl1.SelectedTab = Me.tabListado

        Me.CargarClientes()
        Me.CargarAgentes()
        Me.CargarAeropuertos()
        Me.CargarCiudades()
        Me.CargarAerolineas()
        Me.CargarPaises()
        Me.CargarCHGS()
        Me.CargarWTVAL()
        Me.CargarOtrosCargos()
        Me.CargarUnidades()
        Me.CargarConceptos()

        Me.contadorItems = 400000
        Me.contadorConceptos = 400000

        Me.CargarGrillaItems(True)
        Me.CargarGrillaConceptos(True)
    End Sub



#Region "CargarCombos"

    Public Sub CargarClientes()
        Try
            Dim ds As New DataSet
            ds = oMaestra.GetTabla(CMaestras.Tabla.Cliente)
            If (ds.Tables(0).Rows.Count > 0) Then
                Me.drpCliente.DataSource = CUtil.AgregarRegistro(ds.Tables(0), "Seleccione...")
                Me.drpCliente.ValueMember = ds.Tables(0).Columns(0).ColumnName
                Me.drpCliente.DisplayMember = ds.Tables(0).Columns(1).ColumnName

                Dim dt As DataTable = ds.Tables(0).Copy
                Dim dt2 As DataTable = ds.Tables(0).Copy

                Me.drpClienteBuscar.DataSource = dt
                Me.drpClienteBuscar.ValueMember = dt.Columns(0).ColumnName
                Me.drpClienteBuscar.DisplayMember = dt.Columns(1).ColumnName
                Me.drpEmpresaCarga.DataSource = dt2
                Me.drpEmpresaCarga.ValueMember = dt2.Columns(0).ColumnName
                Me.drpEmpresaCarga.DisplayMember = dt2.Columns(1).ColumnName
            Else
                MessageBox.Show("No se encontraron clientes. Deben ser creados primero", "Clientes", MessageBoxButtons.OK, MessageBoxIcon.Information)
            End If
        Catch ex As Exception
            MessageBox.Show("Ocurrió un error al cargar los clientes: " & ex.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
        End Try
    End Sub

    Public Sub CargarCiudades()
        Try
            Dim ds As New DataSet
            ds = oMaestra.GetCiudades()
            If (ds.Tables(0).Rows.Count > 0) Then
                'Construye una columna con "ciudad - pais"
                ds.Tables(0).Columns.Add("CIUDADPAIS")
                For i As Integer = 0 To ds.Tables(0).Rows.Count - 1
                    ds.Tables(0).Rows(i)("CIUDADPAIS") = ds.Tables(0).Rows(i)("ABREVIATURA").ToString() & "-" & ds.Tables(0).Rows(i)("PAIS").ToString()
                Next

                Dim dr As DataRow = ds.Tables(0).NewRow
                dr(0) = "0"
                dr("CIUDADPAIS") = "Seleccione..."
                ds.Tables(0).Rows.InsertAt(dr, 0)

                Me.drpCiudad.DataSource = ds.Tables(0)
                Me.drpCiudad.ValueMember = ds.Tables(0).Columns(0).ColumnName
                Me.drpCiudad.DisplayMember = "CIUDADPAIS"

                Dim dtTo1 As DataTable = ds.Tables(0).Copy
                Dim dtTo2 As DataTable = ds.Tables(0).Copy
                Dim dtTo3 As DataTable = ds.Tables(0).Copy
                
                Me.drpTo1.DataSource = dtTo1
                Me.drpTo1.ValueMember = dtTo1.Columns(0).ColumnName
                Me.drpTo1.DisplayMember = "CIUDADPAIS"
                Me.drpTo2.DataSource = dtTo2
                Me.drpTo2.ValueMember = dtTo2.Columns(0).ColumnName
                Me.drpTo2.DisplayMember = "CIUDADPAIS"
                Me.drpTo3.DataSource = dtTo3
                Me.drpTo3.ValueMember = dtTo3.Columns(0).ColumnName
                Me.drpTo3.DisplayMember = "CIUDADPAIS"
            Else
                MessageBox.Show("No se encontraron ciudades. Deben ser creadas primero", "Ciudades", MessageBoxButtons.OK, MessageBoxIcon.Information)
            End If
        Catch ex As Exception
            MessageBox.Show("Ocurrió un error al cargar las ciudades: " & ex.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
        End Try
    End Sub

    Public Sub CargarAerolineas()
        Try
            Dim ds As New DataSet
            ds = oMaestra.GetTabla(CMaestras.Tabla.Aerolinea)
            If (ds.Tables(0).Rows.Count > 0) Then
                Dim dr As DataRow = ds.Tables(0).NewRow
                dr(0) = "0"
                dr("ABREVIATURA") = "Seleccione..."
                dr("AEROLINEA") = "Seleccione..."
                ds.Tables(0).Rows.InsertAt(dr, 0)

                Dim dtBy2 As DataTable = ds.Tables(0).Copy
                Dim dtBy3 As DataTable = ds.Tables(0).Copy

                Me.drpBy1.DataSource = ds.Tables(0)
                Me.drpBy1.ValueMember = ds.Tables(0).Columns(0).ColumnName
                Me.drpBy1.DisplayMember = "AEROLINEA"
                Me.drpBy2.DataSource = dtBy2
                Me.drpBy2.ValueMember = dtBy2.Columns(0).ColumnName
                Me.drpBy2.DisplayMember = "AEROLINEA"
                Me.drpBy3.DataSource = dtBy3
                Me.drpBy3.ValueMember = dtBy3.Columns(0).ColumnName
                Me.drpBy3.DisplayMember = "AEROLINEA"
            Else
                MessageBox.Show("No se encontraron aerolíneas. Deben ser creadas primero", "Aerolíneas", MessageBoxButtons.OK, MessageBoxIcon.Information)
            End If
        Catch ex As Exception
            MessageBox.Show("Ocurrió un error al cargar las aerolíneas: " & ex.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
        End Try
    End Sub

    Public Sub CargarPaises()
        'Try
        '    Dim ds As New DataSet
        '    ds = Me.oMaestra.GetCiudades()
        '    If (ds.Tables(1).Rows.Count > 0) Then
        '        Dim dr As DataRow = ds.Tables(1).NewRow
        '        dr(0) = "0"
        '        dr("ABREVIATURA") = "Seleccione..."
        '        ds.Tables(1).Rows.InsertAt(dr, 0)

        '        Me.drpBy2.DataSource = ds.Tables(1)
        '        Me.drpBy2.ValueMember = ds.Tables(1).Columns(0).ColumnName
        '        Me.drpBy2.DisplayMember = "ABREVIATURA"
        '    Else
        '        MessageBox.Show("No se encontraron países. Deben ser creados primero", "Países", MessageBoxButtons.OK, MessageBoxIcon.Information)
        '    End If
        'Catch ex As Exception
        '    MessageBox.Show("Ocurrió un error al cargar los países: " & ex.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
        'End Try
    End Sub

    Public Sub CargarConceptos()
        Try
            Dim ds As New DataSet
            ds = oMaestra.GetConceptosTipo("Guias")
            If (ds.Tables(0).Rows.Count > 0) Then
                Me.dtConceptos = ds.Tables(0).Copy
                Dim dt1 As DataTable = ds.Tables(0).Copy
                Dim dt2 As DataTable = ds.Tables(0).Copy

                Me.drpConcepto.DataSource = CUtil.AgregarRegistro(dt1, "Seleccione...")
                Me.drpConcepto.ValueMember = dt1.Columns(0).ColumnName
                Me.drpConcepto.DisplayMember = dt1.Columns(1).ColumnName
            Else
                MessageBox.Show("No se encontraron conceptos. Deben ser creados primero", "Conceptos", MessageBoxButtons.OK, MessageBoxIcon.Information)
            End If
        Catch ex As Exception
            MessageBox.Show("Ocurrió un error al cargar los conceptos: " & ex.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
        End Try
    End Sub

    Private Sub CargarAgentes()
        'Try
        '    Dim ds As New DataSet
        '    ds = oMaestra.GetTabla(CMaestras.Tabla.Agente)
        '    If (ds.Tables(0).Rows.Count > 0) Then
        '        Me.drpAgente.DataSource = CUtil.AgregarRegistro(ds.Tables(0), "Seleccione...")
        '        Me.drpAgente.ValueMember = ds.Tables(0).Columns(0).ColumnName
        '        Me.drpAgente.DisplayMember = ds.Tables(0).Columns(1).ColumnName
        '    Else
        '        MessageBox.Show("No se encontraron agentes. Deben ser creados primero", "Agentes", MessageBoxButtons.OK, MessageBoxIcon.Information)
        '    End If
        'Catch ex As Exception
        '    MessageBox.Show("Ocurrió un error al cargar los agentes: " & ex.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
        'End Try
    End Sub

    Public Sub CargarAeropuertos()
        Try
            Dim ds As New DataSet
            ds = oMaestra.GetTabla(CMaestras.Tabla.Aeropuerto)
            If (ds.Tables(0).Rows.Count > 0) Then
                Me.drpAeropuertoOrigen.DataSource = CUtil.AgregarRegistro(ds.Tables(0), "Seleccione...")
                Me.drpAeropuertoOrigen.ValueMember = ds.Tables(0).Columns(0).ColumnName
                Me.drpAeropuertoOrigen.DisplayMember = ds.Tables(0).Columns(1).ColumnName

                Dim dt As DataTable = ds.Tables(0).Copy

                Me.drpAeropuertoDestino.DataSource = dt
                Me.drpAeropuertoDestino.ValueMember = dt.Columns(0).ColumnName
                Me.drpAeropuertoDestino.DisplayMember = dt.Columns(1).ColumnName
            Else
                MessageBox.Show("No se encontraron aeropuertos. Deben ser creados primero", "Aeropuertos", MessageBoxButtons.OK, MessageBoxIcon.Information)
            End If
        Catch ex As Exception
            MessageBox.Show("Ocurrió un error al cargar los aeropuertos: " & ex.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
        End Try
    End Sub

    Private Sub CargarCHGS()
        'Construye tabla para cargar el combo de los tipos
        Dim dt As New DataTable
        dt.Columns.Add("ID")
        dt.Columns.Add("VALOR")
        Dim arrValues(1) As String
        arrValues(0) = "0"
        arrValues(1) = "Seleccione..."
        dt.Rows.Add(arrValues)
        arrValues(0) = "PP"
        arrValues(1) = "PP"
        dt.Rows.Add(arrValues)
        arrValues(0) = "CC"
        arrValues(1) = "CC"
        dt.Rows.Add(arrValues)

        Me.drpCHGS.DataSource = dt
        Me.drpCHGS.ValueMember = dt.Columns(0).ColumnName
        Me.drpCHGS.DisplayMember = dt.Columns(1).ColumnName
    End Sub

    Private Sub CargarWTVAL()
        'Construye tabla para cargar el combo de los tipos
        Dim dt As New DataTable
        dt.Columns.Add("ID")
        dt.Columns.Add("VALOR")
        Dim arrValues(1) As String
        arrValues(0) = "0"
        arrValues(1) = "Seleccione..."
        dt.Rows.Add(arrValues)
        arrValues(0) = "PPD"
        arrValues(1) = "PPD"
        dt.Rows.Add(arrValues)
        arrValues(0) = "COLL"
        arrValues(1) = "COLL"
        dt.Rows.Add(arrValues)

        Me.drpWTVAL.DataSource = dt
        Me.drpWTVAL.ValueMember = dt.Columns(0).ColumnName
        Me.drpWTVAL.DisplayMember = dt.Columns(1).ColumnName
    End Sub

    Private Sub CargarOtrosCargos()
        'Construye tabla para cargar el combo de los tipos
        Dim dt As New DataTable
        dt.Columns.Add("ID")
        dt.Columns.Add("VALOR")
        Dim arrValues(1) As String
        arrValues(0) = "0"
        arrValues(1) = "Seleccione..."
        dt.Rows.Add(arrValues)
        arrValues(0) = "PPD"
        arrValues(1) = "PPD"
        dt.Rows.Add(arrValues)
        arrValues(0) = "COLL"
        arrValues(1) = "COLL"
        dt.Rows.Add(arrValues)

        Me.drpOtro.DataSource = dt
        Me.drpOtro.ValueMember = dt.Columns(0).ColumnName
        Me.drpOtro.DisplayMember = dt.Columns(1).ColumnName
    End Sub

    Private Sub CargarUnidades()
        'Construye tabla para cargar el combo de los tipos
        Dim dt As New DataTable
        dt.Columns.Add("ID")
        dt.Columns.Add("UNIDAD")
        Dim arrValues(1) As String
        arrValues(0) = "0"
        arrValues(1) = "Seleccione..."
        dt.Rows.Add(arrValues)
        arrValues(0) = "LIBRA"
        arrValues(1) = "Libra"
        dt.Rows.Add(arrValues)
        arrValues(0) = "KILO"
        arrValues(1) = "Kilo"
        dt.Rows.Add(arrValues)        

        Me.drpItemUnidad.DataSource = dt
        Me.drpItemUnidad.ValueMember = dt.Columns(0).ColumnName
        Me.drpItemUnidad.DisplayMember = dt.Columns(1).ColumnName
    End Sub



#End Region

#Region "Motor de búsqueda"

    Private Sub btnOcultarMenu_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOcultarMenu.Click
        'Muestra/Oculta el panel de los filtros
        If Me.Panel1.Size.Height <= 30 Then
            Me.Panel1.Size = New Size(Me.Panel1.Width, 120)
            Me.btnOcultarMenu.Image = My.Resources.arriba
        Else
            Me.Panel1.Size = New Size(Me.Panel1.Width, 15)
            Me.btnOcultarMenu.Image = My.Resources.abajo
        End If
    End Sub

    Private Sub btnNuevaGuia_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnNuevaGuia.Click
        Me.LimpiarTodo()
        Me.TabControl1.SelectedTab = Me.tabHijas        
    End Sub

    Private Sub grdGuias_CellDoubleClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles grdGuias.CellDoubleClick
        '*** Permite editar o eliminar
        'Se obtiene la info del registro
        Dim id As Integer = Me.grdGuias.Rows(e.RowIndex).Cells("ID").Value        

        Select Case Me.grdGuias.Columns(e.ColumnIndex).Name
            Case "EDITAR"
                Me.EditarGuia(id)
            Case "ELIMINAR"                
                Me.EliminarGuia(id)
        End Select
    End Sub

    Private Sub grdGuias_CellMouseEnter(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles grdGuias.CellMouseEnter
        '*** Coloca la manito cuando el mouse entra en las celdas de editar y eliminar
        If (Me.grdGuias.Columns(e.ColumnIndex).Name = "EDITAR" Or Me.grdGuias.Columns(e.ColumnIndex).Name = "ELIMINAR") Then
            Cursor = Cursors.Hand
        Else
            Cursor = Cursors.Default
        End If

    End Sub

    Private Sub grdGuias_CellMouseMove(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellMouseEventArgs) Handles grdGuias.CellMouseMove
        If (Me.grdGuias.Columns(e.ColumnIndex).Name = "EDITAR" Or Me.grdGuias.Columns(e.ColumnIndex).Name = "ELIMINAR") Then
            Cursor = Cursors.Hand
        Else
            Cursor = Cursors.Default
        End If
    End Sub

    Private Sub btnBuscar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBuscar.Click
        Dim ds As New DataSet
        Try
            Cursor = Cursors.WaitCursor                     
            Dim desde As String = ""
            Dim hasta As String = ""
            Dim mes As String = ""
            Dim dia As String = ""
            If (Me.dateFechaDesde.Checked) Then
                mes = Me.dateFechaDesde.Value.Month
                dia = Me.dateFechaDesde.Value.Day
                If (mes.Length = 1) Then
                    mes = "0" & mes
                End If
                If (dia.Length = 1) Then
                    dia = "0" & dia
                End If
                desde = Me.dateFechaDesde.Value.Year & mes & dia
            End If
            If (Me.dateFechaHasta.Checked) Then
                mes = Me.dateFechaHasta.Value.Month
                dia = Me.dateFechaHasta.Value.Day
                If (mes.Length = 1) Then
                    mes = "0" & mes
                End If
                If (dia.Length = 1) Then
                    dia = "0" & dia
                End If
                hasta = Me.dateFechaHasta.Value.Year & mes & dia
            End If

            ds = Me.oGuia.BuscarGuias(Me.txtBuscarNumero.Text, CInt(Me.drpClienteBuscar.SelectedValue), desde, hasta)

            'Carga la grilla con los resultados obtenidos
            Me.CargarGrillaBusqueda(ds.Tables(0))

            Cursor = Cursors.Default
        Catch ex As Exception
            Cursor = Cursors.Default
            MessageBox.Show("Ocurrió un error al realizar a búsqueda: " & ex.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
        End Try

    End Sub
#End Region

#Region "Métodos privados"

    Private Sub CargarGrillaBusqueda(ByVal tabla As DataTable)
        Me.grdGuias.DataSource = Nothing
        Me.grdGuias.Columns.Clear()

        'Llena grilla de bsuqueda
        If (tabla.Rows.Count > 0) Then
            Me.grdGuias.DataSource = Nothing
            Me.grdGuias.Columns.Clear()
            Me.grdGuias.DataSource = tabla

            Dim iconoEDITAR As New DataGridViewImageColumn()
            iconoEDITAR.ValuesAreIcons = False
            iconoEDITAR.Image = My.Resources.editar
            iconoEDITAR.HeaderText = "EDITAR"
            iconoEDITAR.Name = "EDITAR"
            Me.grdGuias.Columns.Add(iconoEDITAR)

            Dim iconoELIMINAR As New DataGridViewImageColumn()
            iconoELIMINAR.ValuesAreIcons = False
            iconoELIMINAR.Image = My.Resources.eliminar
            iconoELIMINAR.HeaderText = "ELIMINAR"
            iconoELIMINAR.Name = "ELIMINAR"
            Me.grdGuias.Columns.Add(iconoELIMINAR)

            Me.grdGuias.Columns("ID").Visible = False
            Me.grdGuias.Columns("EDITAR").Width = 60
            Me.grdGuias.Columns("ELIMINAR").Width = 70
        Else
            Me.grdGuias.DataSource = Nothing
            Me.grdGuias.Columns.Clear()
            MessageBox.Show("No se encontraron guias con los criterios seleccionados", "", MessageBoxButtons.OK, MessageBoxIcon.Information)
        End If
    End Sub

    Private Sub LimpiarTodo()
        Me.LimpiarItems()
        Me.LimpiarConceptos()
        Me.txtIdentificador1.Text = ""
        Me.txtIdentificador2.Text = ""
        Me.txtIdentificador3.Text = ""
        If (Me.drpEmpresaCarga.Items.Count > 0) Then
            Me.drpEmpresaCarga.SelectedIndex = 0
        End If
        'If (Me.drpAgente.Items.Count > 0) Then
        '    Me.drpAgente.SelectedIndex = 0
        'End If
        If (Me.drpCliente.Items.Count > 0) Then
            Me.drpCliente.SelectedIndex = 0
        End If
        Me.txtInformacionCuenta.Text = ""
        If (Me.drpAeropuertoOrigen.Items.Count > 0) Then
            Me.drpAeropuertoOrigen.SelectedIndex = 0
        End If
        If (Me.drpTo1.Items.Count > 0) Then
            Me.drpTo1.SelectedIndex = 0
        End If
        If (Me.drpTo2.Items.Count > 0) Then
            Me.drpTo2.SelectedIndex = 0
        End If
        If (Me.drpTo3.Items.Count > 0) Then
            Me.drpTo3.SelectedIndex = 0
        End If
        If (Me.drpBy1.Items.Count > 0) Then
            Me.drpBy1.SelectedIndex = 0
        End If
        If (Me.drpBy2.Items.Count > 0) Then
            Me.drpBy2.SelectedIndex = 0
        End If
        If (Me.drpBy3.Items.Count > 0) Then
            Me.drpBy3.SelectedIndex = 0
        End If
        If (Me.drpOtro.Items.Count > 0) Then
            Me.drpOtro.SelectedIndex = 0
        End If
        Me.txtAirWaybill.Text = ""
        Me.drpCHGS.SelectedIndex = 0
        Me.drpWTVAL.SelectedIndex = 0
        Me.txtNumeroVuelo.Text = ""
        Me.txtAccountNumber.Text = ""
        Me.dateFecha.Value = Date.Today
        If (Me.drpCiudad.Items.Count > 0) Then
            Me.drpCiudad.SelectedIndex = 0
        End If
        Me.txtHandlingInformation.Text = ""
        Me.dtItems.Rows.Clear()
        Me.dtOtrosCargos.Rows.Clear()
        Me.idItem = 0
        Me.idConcepto = 0
        Me.idGuia = 0
    End Sub

    Private Sub LimpiarItems()
        Me.idItem = 0        
        Me.drpItemUnidad.SelectedIndex = 0
        Me.txtItemCantidad.Text = ""
        Me.txtItemDescripcion.Text = ""
        Me.txtItemPeso.Text = ""
        Me.chargeableWeightCalculado = 0
        Me.txtItemPesoCarga.Text = ""
        Me.txtItemRata.Text = ""
        Me.txtFS.Text = ""
        Me.txtFS2.Text = ""
    End Sub

    Private Sub LimpiarConceptos()
        Me.idConcepto = 0
        If (Me.drpConcepto.Items.Count = 0) Then
            Me.drpConcepto.Items.Add("No existen conceptos")
        End If
        Me.txtValorOtroCargo.Text = ""
        Me.txtFS2Concepto.Text = ""
    End Sub

    Private Sub CargarGrillaItems(ByVal consultaBD As Boolean)
        Try
            Cursor = Cursors.WaitCursor
            Me.grdItems.DataSource = Nothing
            Me.grdItems.Columns.Clear()

            If (consultaBD) Then
                Dim ds As New DataSet
                ds = Me.oGuia.GetItemsGuia(Me.idGuia)
                Me.dtItems = ds.Tables(0).Copy
            End If

            If (Me.dtItems.Rows.Count > 0) Then
                Me.grdItems.DataSource = Me.dtItems
                Dim iconoEDITAR As New DataGridViewImageColumn()
                iconoEDITAR.ValuesAreIcons = False
                iconoEDITAR.Image = My.Resources.editar
                iconoEDITAR.HeaderText = "EDITAR"
                iconoEDITAR.Name = "EDITAR"
                Me.grdItems.Columns.Add(iconoEDITAR)

                Dim iconoELIMINAR As New DataGridViewImageColumn()
                iconoELIMINAR.ValuesAreIcons = False
                iconoELIMINAR.Image = My.Resources.eliminar
                iconoELIMINAR.HeaderText = "ELIMINAR"
                iconoELIMINAR.Name = "ELIMINAR"
                Me.grdItems.Columns.Add(iconoELIMINAR)

                Me.grdItems.Columns("ID").Visible = False
                Me.grdItems.Columns("EDITAR").Width = 60
                Me.grdItems.Columns("ELIMINAR").Width = 70
            End If
            Cursor = Cursors.Default
        Catch ex As Exception
            Cursor = Cursors.Default
            MessageBox.Show("Ocurrió un error al cargar los ítems: " & ex.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
        End Try
    End Sub

    Private Sub CargarGrillaConceptos(ByVal consultaBD As Boolean)
        Try
            Cursor = Cursors.WaitCursor
            Me.grdOtroCargo.DataSource = Nothing
            Me.grdOtroCargo.Columns.Clear()

            If (consultaBD) Then
                Dim ds As New DataSet
                ds = Me.oGuia.GetConceptosGuia(Me.idGuia)
                Me.dtOtrosCargos = ds.Tables(0).Copy
            End If

            If (Me.dtOtrosCargos.Rows.Count > 0) Then
                Me.grdOtroCargo.DataSource = Me.dtOtrosCargos
                Dim iconoEDITAR As New DataGridViewImageColumn()
                iconoEDITAR.ValuesAreIcons = False
                iconoEDITAR.Image = My.Resources.editar
                iconoEDITAR.HeaderText = "EDITAR"
                iconoEDITAR.Name = "EDITAR"
                Me.grdOtroCargo.Columns.Add(iconoEDITAR)

                Dim iconoELIMINAR As New DataGridViewImageColumn()
                iconoELIMINAR.ValuesAreIcons = False
                iconoELIMINAR.Image = My.Resources.eliminar
                iconoELIMINAR.HeaderText = "ELIMINAR"
                iconoELIMINAR.Name = "ELIMINAR"
                Me.grdOtroCargo.Columns.Add(iconoELIMINAR)

                Me.grdOtroCargo.Columns("ID").Visible = False                
                Me.grdOtroCargo.Columns("IDCONCEPTO").Visible = False
                Me.grdOtroCargo.Columns("EDITAR").Width = 60
                Me.grdOtroCargo.Columns("ELIMINAR").Width = 70
            End If
            Cursor = Cursors.Default
        Catch ex As Exception
            Cursor = Cursors.Default
            MessageBox.Show("Ocurrió un error al cargar 'Otros cargos': " & ex.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
        End Try
    End Sub


    Private Function ValidarItem() As Boolean
        Dim mensaje As String = ""
        If (Me.drpItemUnidad.SelectedValue = "0") Then
            mensaje += "- Debe seleccionar la unidad de peso"
        End If

        If (Me.txtItemDescripcion.Text = "") Then
            mensaje += "- Debe describir el producto"
        End If

        If (Trim(Me.txtItemCantidad.Text).Length = 0) Then
            mensaje += "- Debe escribir la cantidad" & Chr(13)
        Else
            If Not IsNumeric(Trim(Me.txtItemCantidad.Text)) Then
                mensaje += "- La cantidad debe ser un valor numérico" & Chr(13)
            End If
        End If
        If (Trim(Me.txtItemPeso.Text).Length = 0) Then
            mensaje += "- Debe escribir el peso" & Chr(13)
        Else
            If Not IsNumeric(Trim(Me.txtItemPeso.Text)) Then
                mensaje += "- El peso debe ser un valor numérico" & Chr(13)
            End If
        End If
        If (Trim(Me.txtItemPesoCarga.Text).Length = 0) Then
            mensaje += "- Debe escribir el peso de la cagra" & Chr(13)
        Else
            If Not IsNumeric(Trim(Me.txtItemPesoCarga.Text)) Then
                mensaje += "- El peso de la carga debe ser un valor numérico" & Chr(13)
            End If
        End If
        If (Trim(Me.txtItemRata.Text).Length = 0) Then
            mensaje += "- Debe escribir el valor de la rata" & Chr(13)
        Else
            If Not IsNumeric(Trim(Me.txtItemRata.Text)) Then
                mensaje += "- El valor de la rata debe ser numérico" & Chr(13)
            End If
        End If
        If (Trim(Me.txtFS.Text).Length > 0) Then
            If Not IsNumeric(Trim(Me.txtFS.Text)) Then
                mensaje += "- El valor FS debe ser un valor numérico" & Chr(13)
            End If
        End If
        If (Trim(Me.txtFS2.Text).Length > 0) Then
            If Not IsNumeric(Trim(Me.txtFS2.Text)) Then
                mensaje += "- El valor FS2 debe ser un valor numérico" & Chr(13)
            End If
        End If

        If (mensaje.Length > 0) Then
            MessageBox.Show(mensaje, "Datos incompletos", MessageBoxButtons.OK, MessageBoxIcon.Information)
            Return False
        Else
            Return True
        End If

    End Function

    Public Function ValidarOtroCargo() As Boolean
        Dim mensaje As String = ""

        Dim tipo As String = ""
        Dim valor As Double = 0
        Dim iva As Integer = 0
        Dim minimo As Double = 0
        Dim dueAgent As Integer = 0
        If (Me.drpConcepto.SelectedValue = "0") Then
            MessageBox.Show("- Debe seleccionar el concepto", "Datos incompletos", MessageBoxButtons.OK, MessageBoxIcon.Information)
            Return False
        Else
            'Se obtiene la info del concepto que se va a agregar
            For i As Integer = 0 To Me.dtConceptos.Rows.Count - 1
                If (Me.dtConceptos.Rows(i)("ID").ToString = Me.drpConcepto.SelectedValue) Then
                    tipo = Me.dtConceptos.Rows(i)("TIPO")
                    valor = Me.dtConceptos.Rows(i)("VALOR")
                    iva = Me.dtConceptos.Rows(i)("IVA")
                    minimo = Me.dtConceptos.Rows(i)("MINIMO")
                    If (Me.dtConceptos.Rows(i)("DUEAGENT").ToString = "1") Then
                        dueAgent = 1
                    End If
                    Exit For
                End If
            Next

            Select Case tipo
                Case "PORCENTAJE"
                    mensaje += "- Este concepto no se puede agregar porque se calcula como porcentaje" & Chr(13)
                Case "KILOS"
                    mensaje += "- Este concepto no se puede agregar porque se calcula de acuerdo al peso" & Chr(13)
            End Select
        End If

        If (Trim(Me.txtValorOtroCargo.Text).Length = 0) Then
            mensaje += "- Debe escribir el valor" & Chr(13)
        Else
            If Not IsNumeric(Trim(Me.txtValorOtroCargo.Text)) Then
                mensaje += "- El valor debe ser numérico" & Chr(13)
            Else
                'Si existe un valor minimo se valida que el valor escrito sea mayor
                If (minimo > 0) And (minimo > CDbl(Me.txtValorOtroCargo.Text)) Then
                    mensaje += "- El valor mínimo para esta concepto es " & minimo.ToString() & Chr(13)
                End If
            End If
        End If

        If (Trim(Me.txtFS2Concepto.Text).Length > 0) Then
            If Not IsNumeric(Trim(Me.txtFS2Concepto.Text)) Then
                mensaje += "- El valor de FS2 debe ser numérico" & Chr(13)
            End If
        End If

        If (mensaje.Length > 0) Then
            MessageBox.Show(mensaje, "Datos incompletos", MessageBoxButtons.OK, MessageBoxIcon.Information)
            Return False
        Else
            Return True
        End If

    End Function

    Public Function Validar() As Boolean
        Dim mensaje As String = ""

        If (Me.txtIdentificador1.Text = "") And (Me.txtIdentificador2.Text = "") And (Me.txtIdentificador3.Text = "") Then
            mensaje += "- Debe escribir el identificador de la guía" & Chr(13)
        End If
        If (Me.drpEmpresaCarga.SelectedValue = "0") Then
            mensaje += "- Debe seleccionar la empresa de carga" & Chr(13)
        End If
        'If (Me.drpAgente.SelectedValue = "0") Then
        '    mensaje += "- Debe seleccionar el agente" & Chr(13)
        'End If
        If (Me.txtAirWaybill.Text.Trim = "") Then
            mensaje += "- Debe escribir el Air Waybill" & Chr(13)
        End If
        If (Me.drpCliente.SelectedValue = "0") Then
            mensaje += "- Debe seleccionar el cliente" & Chr(13)
        End If
        If (Me.txtInformacionCuenta.Text = "") Then
            mensaje += "- Debe escribir la información de la cuenta" & Chr(13)
        End If
        If (Me.drpAeropuertoOrigen.SelectedValue = "0") Then
            mensaje += "- Debe seleccionar el aeropuerto origen" & Chr(13)
        End If
        If (Me.drpAeropuertoDestino.SelectedValue = "0") Then
            mensaje += "- Debe seleccionar el aeropuerto destino" & Chr(13)
        End If
        'If (Me.drpTo1.SelectedValue = "0") Or (Me.drpBy1.SelectedValue = "0") Then
        '    mensaje += "- Debe seleccionar las ciudades (To y By)" & Chr(13)
        'End If
        If (Me.drpCHGS.SelectedValue = "0") Then
            mensaje += "- Debe seleccionar CHGS" & Chr(13)
        End If
        If (Me.drpWTVAL.SelectedValue = "0") Then
            mensaje += "- Debe seleccionar WT / VAL" & Chr(13)
        End If
        If (Me.drpOtro.SelectedValue = "0") Then
            mensaje += "- Debe seleccionar la información de 'Otro'" & Chr(13)
        End If
        If (Me.txtNumeroVuelo.Text = "") Then
            mensaje += "- Debe escribir el número de vuelo" & Chr(13)
        End If
        If (Me.drpCiudad.SelectedValue = "0") Then
            mensaje += "- Debe seleccionar la ciudad" & Chr(13)
        End If

        If (mensaje.Length > 0) Then
            MessageBox.Show(mensaje, "Datos incompletos", MessageBoxButtons.OK, MessageBoxIcon.Information)
            Return False
        Else
            Return True
        End If

    End Function

    Private Sub EliminarItem(ByVal indice As Integer, ByVal id As Integer)
        Try
            If (MessageBox.Show("¿Realmente desea eliminar este ítem?", "Eliminar", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes) Then
                Cursor = Cursors.WaitCursor
                'Si el id es cero, simplemente se elimina del datatable porque aun no esta en la bd
                If (id > 0) Then
                    Me.oGuia.EliminarItemGuia(id)
                End If
                Me.dtItems.Rows.RemoveAt(indice)
                Me.dtItems.AcceptChanges()
                Cursor = Cursors.Default
                MessageBox.Show("El ítem ha sido eliminado", "Ítem eliminado", MessageBoxButtons.OK, MessageBoxIcon.Information)
            End If
        Catch ex As Exception
            Cursor = Cursors.Default
            MessageBox.Show("NO se eliminó el ítem: " & ex.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
        End Try
    End Sub

    Private Sub EliminarConcepto(ByVal indice As Integer, ByVal id As Integer)
        Try
            If (MessageBox.Show("¿Realmente desea eliminar este concepto?", "Eliminar", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes) Then
                Cursor = Cursors.WaitCursor
                'Si el id es cero, simplemente se elimina del datatable porque aun no esta en la bd
                If (id > 0) Then
                    Me.oGuia.EliminarConceptoGuia(id)
                End If
                Me.dtOtrosCargos.Rows.RemoveAt(indice)
                Me.dtOtrosCargos.AcceptChanges()
                Cursor = Cursors.Default
                MessageBox.Show("El concepto ha sido eliminado", "Concepto eliminado", MessageBoxButtons.OK, MessageBoxIcon.Information)
            End If
        Catch ex As Exception
            Cursor = Cursors.Default
            MessageBox.Show("NO se eliminó el concepto: " & ex.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
        End Try
    End Sub

    Private Sub EliminarGuia(ByVal id As Integer)
        Try
            If (MessageBox.Show("¿Realmente desea eliminar esta guía?", "Eliminar guía", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes) Then
                Cursor = Cursors.WaitCursor
                Me.oGuia.EliminarGuia(id)

                'elimina del datatable el registro
                Dim dtG As DataTable = CType(Me.grdGuias.DataSource, DataTable)
                For i As Integer = 0 To dtG.Rows.Count - 1
                    If (dtG.Rows(i)("ID").ToString = id.ToString) Then
                        dtG.Rows.RemoveAt(i)
                        Exit For
                    End If
                Next
                dtG.AcceptChanges()

                Cursor = Cursors.Default
                MessageBox.Show("La guía ha sido eliminada", "Guía eliminada", MessageBoxButtons.OK, MessageBoxIcon.Information)
            End If
        Catch ex As Exception
            Cursor = Cursors.Default
            MessageBox.Show("NO se eliminó la guía: " & ex.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
        End Try
    End Sub

    Private Sub EditarGuia(ByVal id As Integer)
        Me.LimpiarTodo()
        Me.idGuia = id
        Me.TraerDatosGuia(id)
        Me.TabControl1.SelectedTab = Me.tabHijas        
    End Sub

    Private Sub TraerDatosGuia(ByVal id As Integer)
        '*** Trae la informacion de la guia y llena los controles y grillas. Si el id le llega 0 es
        '*** porque se va a crear una nueva guia, tonces se limpian todos los controles
        If (id = 0) Then
            Me.LimpiarTodo()
            Me.idGuia = 0
        Else
            Try
                Cursor = Cursors.WaitCursor
                Me.idGuia = id
                Dim ds As New DataSet
                ds = Me.oGuia.GetGuiaById(Me.idGuia)

                If (ds.Tables(0).Rows.Count > 0) Then
                    Me.txtIdentificador1.Text = ds.Tables(0).Rows(0)("IDENTIFICADOR1")
                    Me.txtIdentificador2.Text = ds.Tables(0).Rows(0)("IDENTIFICADOR2")
                    Me.txtIdentificador3.Text = ds.Tables(0).Rows(0)("IDENTIFICADOR3")
                    Me.drpEmpresaCarga.SelectedValue = ds.Tables(0).Rows(0)("EMPRESACARGA")
                    'Me.drpAgente.SelectedValue = ds.Tables(0).Rows(0)("IDAGENTE")
                    Me.txtAirWaybill.Text = ds.Tables(0).Rows(0)("AIRWAYBILL")
                    Me.drpCliente.SelectedValue = ds.Tables(0).Rows(0)("IDCLIENTE")
                    Me.txtInformacionCuenta.Text = ds.Tables(0).Rows(0)("INFORMACIONCUENTA")
                    Me.txtAccountNumber.Text = ds.Tables(0).Rows(0)("ACCOUNTNUMBER")
                    Me.drpAeropuertoOrigen.SelectedValue = ds.Tables(0).Rows(0)("IDAEROPUERTOORIGEN")
                    Me.drpAeropuertoDestino.SelectedValue = ds.Tables(0).Rows(0)("IDAEROPUERTODESTINO")
                    Me.drpTo1.SelectedValue = ds.Tables(0).Rows(0)("TO1")
                    Me.drpTo2.SelectedValue = ds.Tables(0).Rows(0)("TO2")
                    Me.drpTo3.SelectedValue = ds.Tables(0).Rows(0)("TO3")                    
                    Me.drpBy1.SelectedValue = "0"
                    If ds.Tables(0).Rows(0)("BY1") IsNot DBNull.Value Then                        
                        Me.drpBy1.SelectedValue = ds.Tables(0).Rows(0)("BY1")
                    End If

                    Me.drpBy2.SelectedValue = "0"
                    If ds.Tables(0).Rows(0)("BY2") IsNot DBNull.Value Then
                        Me.drpBy2.SelectedValue = ds.Tables(0).Rows(0)("BY2")
                    End If
                    Me.drpBy3.SelectedValue = "0"
                    If ds.Tables(0).Rows(0)("BY3") IsNot DBNull.Value Then                        
                        Me.drpBy3.SelectedValue = ds.Tables(0).Rows(0)("BY3")                    
                    End If
                    

                    Me.drpCHGS.SelectedValue = ds.Tables(0).Rows(0)("CHGS")
                    Me.drpWTVAL.SelectedValue = ds.Tables(0).Rows(0)("WTVAL")
                    Me.drpOtro.SelectedValue = ds.Tables(0).Rows(0)("OTRO")
                    Me.txtNumeroVuelo.Text = ds.Tables(0).Rows(0)("NUMEROVUELO")
                    Me.dateFecha.Value = ds.Tables(0).Rows(0)("FECHA")
                    Me.drpCiudad.SelectedValue = ds.Tables(0).Rows(0)("IDCIUDAD")
                    Me.txtHandlingInformation.Text = ds.Tables(0).Rows(0)("HANDLINGINFORMATION")
                    If (ds.Tables(0).Rows(0)("TIPO").ToString() = "PREPAID") Then
                        Me.rbtnPrepaid.Checked = True
                        Me.rbtnCollect.Checked = False
                    Else
                        Me.rbtnPrepaid.Checked = False
                        Me.rbtnCollect.Checked = True
                    End If
                End If
        Cursor = Cursors.Default
            Catch ex As Exception
            Cursor = Cursors.Default
            MessageBox.Show("Ocurrió un error al traer la información de la guía: " & ex.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
        End Try
        End If

        Me.CargarGrillaItems(True)
        Me.CargarGrillaConceptos(True)        
    End Sub



#End Region

#Region "Botones que abren otros formularios"

    Private Sub btnCrearCliente_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCrearCliente.Click
        My.Forms.Clientes.MdiParent = My.Forms.Principal
        My.Forms.Clientes.Show()
    End Sub

    Private Sub btnCrearAeropuerto_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCrearAeropuerto.Click
        My.Forms.Aeropuertos.MdiParent = My.Forms.Principal
        My.Forms.Aeropuertos.Show()
    End Sub

    Private Sub btnCrearAeropuerto2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCrearAeropuerto2.Click
        My.Forms.Aeropuertos.MdiParent = My.Forms.Principal
        My.Forms.Aeropuertos.Show()
    End Sub

    Private Sub btnCrearConcepto_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCrearConcepto.Click
        My.Forms.Conceptos.MdiParent = My.Forms.Principal
        My.Forms.Conceptos.Show()
    End Sub

    Private Sub btnDimensiones_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDimensiones.Click
        If (Me.idItem = 0) Then
            MessageBox.Show("Debe seleccionar el ítem al que desea agregar las dimensiones", "", MessageBoxButtons.OK, MessageBoxIcon.Information)
        Else
            My.Forms.Dimensiones.MdiParent = My.Forms.Principal
            My.Forms.Dimensiones.idItemGuia = Me.idItem
            My.Forms.Dimensiones.Show()
        End If
    End Sub

#End Region

#Region "Items y conceptos"

    Private Sub btnListoItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnListoItem.Click
        If (Me.ValidarItem()) Then
            Try
                Cursor = Cursors.WaitCursor

                'Se obtiene la info del concepto que se va a agregar
                Dim unidad As String = Me.drpItemUnidad.SelectedValue
                Dim cantidad As Double = 0
                Dim peso As Double = 0
                Dim pesoCarga As Double = 0
                Dim rata As Double = 0
                Dim fs As Double = 0
                Dim fs2 As Double = 0


                'Si se esta editando lo modifica en la tabla
                If (Me.idItem > 0) Then
                    For i As Integer = 0 To Me.dtItems.Rows.Count - 1
                        If (Me.dtItems.Rows(i)("ID").ToString = Me.idItem.ToString) Then
                            Me.dtItems.Rows(i)("CANTIDAD") = Me.txtItemCantidad.Text
                            Me.dtItems.Rows(i)("PESO") = Me.txtItemPeso.Text
                            Me.dtItems.Rows(i)("UNIDAD") = Me.drpItemUnidad.SelectedValue
                            Me.dtItems.Rows(i)("PESOCARGA") = Me.txtItemPesoCarga.Text
                            Me.dtItems.Rows(i)("RATA") = Me.txtItemRata.Text
                            Me.dtItems.Rows(i)("PRODUCTO") = Me.txtItemDescripcion.Text
                            If (Me.txtFS.Text.Length > 0) Then
                                Me.dtItems.Rows(i)("FS") = Me.txtFS.Text
                            Else
                                Me.dtItems.Rows(i)("FS") = DBNull.Value
                            End If
                            If (Me.txtFS2.Text.Length > 0) Then
                                Me.dtItems.Rows(i)("FS2") = Me.txtFS2.Text
                            Else
                                Me.dtItems.Rows(i)("FS2") = DBNull.Value
                            End If
                        End If
                    Next
                Else
                    'Se esta agregando un nuevo registro, se agrega a la tabla                    
                    Dim dr As DataRow
                    dr = Me.dtItems.NewRow
                    dr("ID") = Me.contadorItems
                    Me.contadorItems = Me.contadorItems + 1
                    dr("CANTIDAD") = Me.txtItemCantidad.Text
                    dr("PESO") = Me.txtItemPeso.Text
                    dr("UNIDAD") = Me.drpItemUnidad.SelectedValue
                    dr("PESOCARGA") = Me.txtItemPesoCarga.Text
                    dr("RATA") = Me.txtItemRata.Text
                    dr("PRODUCTO") = Me.txtItemDescripcion.Text
                    If (Me.txtFS.Text.Length > 0) Then
                        dr("FS") = Me.txtFS.Text
                    Else
                        dr("FS") = DBNull.Value
                    End If
                    If (Me.txtFS2.Text.Length > 0) Then
                        dr("FS2") = Me.txtFS2.Text
                    Else
                        dr("FS2") = DBNull.Value
                    End If

                    Me.dtItems.Rows.Add(dr)
                End If
                Me.dtItems.AcceptChanges()

                'Recarga la grilla 
                Me.CargarGrillaItems(False)

                Me.LimpiarItems()
                Cursor = Cursors.Default
            Catch ex As Exception
                Cursor = Cursors.Default
                MessageBox.Show("Ocurrió un error al agregar el ítem: " & ex.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
            End Try

        End If
    End Sub

    Private Sub btnListoOtroCargo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnListoOtroCargo.Click
        '*** Agrega o edita el registro a la tabla y recarga la grilla 
        If (Me.ValidarOtroCargo()) Then
            Try
                Cursor = Cursors.WaitCursor

                'Se obtiene la info del concepto que se va a agregar
                Dim tipo As String = ""
                Dim valor As Double = 0
                Dim iva As Boolean = False
                Dim minimo As Double = 0
                Dim dueAgent As Integer = 0
                Dim fs2 As Double = 0
                For i As Integer = 0 To Me.dtConceptos.Rows.Count - 1
                    If (Me.dtConceptos.Rows(i)("ID").ToString = Me.drpConcepto.SelectedValue) Then
                        tipo = Me.dtConceptos.Rows(i)("TIPO")
                        valor = Me.dtConceptos.Rows(i)("VALOR")
                        iva = Me.dtConceptos.Rows(i)("IVA")
                        minimo = Me.dtConceptos.Rows(i)("MINIMO")                        
                        Exit For
                    End If
                Next

                'Si se esta editando un registro lo modifica en la tabla
                If (Me.idConcepto > 0) Then
                    For i As Integer = 0 To Me.dtOtrosCargos.Rows.Count - 1
                        If (Me.dtOtrosCargos.Rows(i)("ID").ToString = Me.idConcepto.ToString) Then
                            Me.dtOtrosCargos.Rows(i)("IDCONCEPTO") = Me.drpConcepto.SelectedValue
                            Me.dtOtrosCargos.Rows(i)("VALOR") = Me.txtValorOtroCargo.Text
                            If (iva) Then
                                Me.dtOtrosCargos.Rows(i)("CONCEPTO") = Me.drpConcepto.Text
                                Me.dtOtrosCargos.Rows(i)("IVA") = CDbl(Me.txtValorOtroCargo.Text) * 0.16
                            Else
                                Me.dtOtrosCargos.Rows(i)("CONCEPTO") = Me.drpConcepto.Text & " (Sin IVA)"
                                Me.dtOtrosCargos.Rows(i)("IVA") = 0
                            End If
                            If (Me.txtFS2Concepto.Text.Length > 0) Then
                                Me.dtOtrosCargos.Rows(i)("FS2") = Me.txtFS2Concepto.Text
                            Else
                                Me.dtOtrosCargos.Rows(i)("FS2") = DBNull.Value
                            End If
                        End If
                    Next
                Else
                    'Se esta agregando un nuevo registro, se agrega a la tabla                    
                    Dim dr As DataRow
                    dr = Me.dtOtrosCargos.NewRow
                    dr("ID") = Me.contadorConceptos
                    Me.contadorConceptos = Me.contadorConceptos + 1

                    dr("IDCONCEPTO") = Me.drpConcepto.SelectedValue
                    If (iva) Then
                        dr("CONCEPTO") = Me.drpConcepto.Text
                    Else
                        dr("CONCEPTO") = Me.drpConcepto.Text & " (Sin IVA)"
                    End If
                    dr("VALOR") = Me.txtValorOtroCargo.Text
                    If (iva) Then
                        dr("IVA") = CDbl(Me.txtValorOtroCargo.Text) * 0.16
                    Else
                        dr("IVA") = 0
                    End If
                    If (Me.txtFS2Concepto.Text.Length > 0) Then
                        dr("FS2") = Me.txtFS2Concepto.Text
                    Else
                        dr("FS2") = DBNull.Value
                    End If

                    Me.dtOtrosCargos.Rows.Add(dr)
                End If
                Me.dtOtrosCargos.AcceptChanges()

                'Recarga la grilla 
                Me.CargarGrillaConceptos(False)                
                Me.LimpiarConceptos()
                Cursor = Cursors.Default
            Catch ex As Exception
                Cursor = Cursors.Default
                MessageBox.Show("Ocurrió un error al agregar el concepto: " & ex.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
            End Try
        End If

    End Sub

    Private Sub btnCancelarItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancelarItem.Click
        Me.LimpiarItems()
    End Sub

    Private Sub btnCancelarOtroCargo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancelarOtroCargo.Click
        Me.LimpiarConceptos()
    End Sub

    Private Sub txtItemPesoCarga_Leave(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtItemPesoCarga.Leave
        'Cuando se cambia el valor de este textbox (gross weight) se recalcula el valor de Chargeable Weight        
        Me.ActualizarChargeableWeight()
    End Sub
#End Region

#Region "Eventos de grillas"


    Private Sub grdItems_CellMouseEnter(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles grdItems.CellMouseEnter
        '*** Coloca la manito cuando el mouse entra en las celdas de editar y eliminar
        If (Me.grdItems.Columns(e.ColumnIndex).Name = "EDITAR" Or Me.grdItems.Columns(e.ColumnIndex).Name = "ELIMINAR") Then
            Cursor = Cursors.Hand
        Else
            Cursor = Cursors.Default
        End If

    End Sub

    Private Sub grdItems_CellMouseMove(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellMouseEventArgs) Handles grdItems.CellMouseMove
        If (Me.grdItems.Columns(e.ColumnIndex).Name = "EDITAR" Or Me.grdItems.Columns(e.ColumnIndex).Name = "ELIMINAR") Then
            Cursor = Cursors.Hand
        Else
            Cursor = Cursors.Default
        End If

    End Sub

    Private Sub grdOtroCargo_CellMouseEnter(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles grdOtroCargo.CellMouseEnter
        '*** Coloca la manito cuando el mouse entra en las celdas de editar y eliminar
        If (Me.grdOtroCargo.Columns(e.ColumnIndex).Name = "EDITAR" Or Me.grdOtroCargo.Columns(e.ColumnIndex).Name = "ELIMINAR") Then
            Cursor = Cursors.Hand
        Else
            Cursor = Cursors.Default
        End If
    End Sub

    Private Sub grdOtroCargo_CellMouseMove(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellMouseEventArgs) Handles grdOtroCargo.CellMouseMove
        If (Me.grdOtroCargo.Columns(e.ColumnIndex).Name = "EDITAR" Or Me.grdOtroCargo.Columns(e.ColumnIndex).Name = "ELIMINAR") Then
            Cursor = Cursors.Hand
        Else
            Cursor = Cursors.Default
        End If

    End Sub

    Private Sub grdItems_CellDoubleClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles grdItems.CellDoubleClick
        '*** Permite editar o eliminar
        'Se obtiene la info del registro
        Dim id As Integer = Me.grdItems.Rows(e.RowIndex).Cells("ID").Value
        Dim cantidad As Double = Me.grdItems.Rows(e.RowIndex).Cells("CANTIDAD").Value
        Dim peso As Double = Me.grdItems.Rows(e.RowIndex).Cells("PESO").Value
        Dim unidad As String = Me.grdItems.Rows(e.RowIndex).Cells("UNIDAD").Value
        Dim pesoCarga As Double = Me.grdItems.Rows(e.RowIndex).Cells("PESOCARGA").Value
        Dim rata As Double = Me.grdItems.Rows(e.RowIndex).Cells("RATA").Value
        Dim producto As String = Me.grdItems.Rows(e.RowIndex).Cells("PRODUCTO").Value
        Dim fs As String = Me.grdItems.Rows(e.RowIndex).Cells("FS").Value.ToString()
        Dim fs2 As String = Me.grdItems.Rows(e.RowIndex).Cells("FS2").Value.ToString()

        Select Case Me.grdItems.Columns(e.ColumnIndex).Name
            Case "EDITAR"
                Me.idItem = id
                Me.txtItemCantidad.Text = cantidad
                Me.txtItemPeso.Text = peso
                Me.chargeableWeightCalculado = peso
                Me.drpItemUnidad.SelectedValue = unidad
                Me.txtItemPesoCarga.Text = pesoCarga
                Me.txtItemRata.Text = rata
                Me.txtItemDescripcion.Text = producto
                Me.txtFS.Text = fs
                Me.txtFS2.Text = fs2
            Case "ELIMINAR"
                Me.EliminarItem(e.RowIndex, id)
        End Select
    End Sub

    Private Sub grdOtroCargo_CellDoubleClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles grdOtroCargo.CellDoubleClick
        '*** Permite editar o eliminar
        'Se obtiene la info del registro
        Dim id As Integer = Me.grdOtroCargo.Rows(e.RowIndex).Cells("ID").Value
        Dim idConcepto As Integer = Me.grdOtroCargo.Rows(e.RowIndex).Cells("IDCONCEPTO").Value
        Dim valor As Double = Me.grdOtroCargo.Rows(e.RowIndex).Cells("VALOR").Value
        Dim iva As Double = Me.grdOtroCargo.Rows(e.RowIndex).Cells("IVA").Value
        Dim fs2 As String = Me.grdOtroCargo.Rows(e.RowIndex).Cells("FS2").Value.ToString()

        Select Case Me.grdOtroCargo.Columns(e.ColumnIndex).Name
            Case "EDITAR"
                Me.idConcepto = id
                Me.drpConcepto.SelectedValue = idConcepto
                Me.txtValorOtroCargo.Text = valor
                Me.txtFS2Concepto.Text = fs2
            Case "ELIMINAR"
                Me.EliminarConcepto(e.RowIndex, id)
        End Select
    End Sub


#End Region

#Region "Metodos publicos"

    Public Sub ActualizarChargeableWeight()
        Dim grossWeight As Double = 0
        If (Me.txtItemPesoCarga.Text.Length > 0) Then
            grossWeight = CDbl(Me.txtItemPesoCarga.Text)
        End If

        Dim valor As Double
        If (Me.chargeableWeightCalculado < grossWeight) Then
            valor = grossWeight
        Else
            valor = Me.chargeableWeightCalculado
        End If

        Me.txtItemPeso.Text = valor        
    End Sub

#End Region


    Private Sub btnListo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnListo.Click
        '*** Guarda en la bd la info que se esta editando o creando
        If (Me.Validar()) Then
            Try
                Cursor = Cursors.WaitCursor

                Dim fecha As String = ""
                Dim mes As String = ""
                Dim dia As String = ""

                If (Me.dateFecha.Checked) Then
                    mes = Me.dateFecha.Value.Month
                    dia = Me.dateFecha.Value.Day
                    If (mes.Length = 1) Then
                        mes = "0" & mes
                    End If
                    If (dia.Length = 1) Then
                        dia = "0" & dia
                    End If
                    fecha = Me.dateFecha.Value.Year & mes & dia
                End If

                Dim tipoGuia As String = "PREPAID"
                If (Me.rbtnCollect.Checked) Then
                    tipoGuia = "COLLECT"
                End If

                Me.idGuia = Me.oGuia.ActualizarGuia(Me.idGuia, Me.txtIdentificador1.Text, Me.txtIdentificador2.Text, Me.txtIdentificador3.Text, CInt(Me.drpEmpresaCarga.SelectedValue), 0, CInt(Me.drpCliente.SelectedValue), Me.txtInformacionCuenta.Text, CInt(Me.drpAeropuertoOrigen.SelectedValue), CInt(Me.drpAeropuertoDestino.SelectedValue), CInt(Me.drpTo1.SelectedValue), CInt(Me.drpTo2.SelectedValue), CInt(Me.drpBy1.SelectedValue), CInt(Me.drpBy2.SelectedValue), Me.drpCHGS.SelectedValue, Me.drpWTVAL.SelectedValue, Me.drpOtro.SelectedValue, Me.txtNumeroVuelo.Text, fecha, CInt(Me.drpCiudad.SelectedValue), tipoGuia, Me.txtAccountNumber.Text, CInt(Me.drpTo3.SelectedValue), CInt(Me.drpBy3.SelectedValue), Me.txtAirWaybill.Text.Trim(), Me.txtHandlingInformation.Text.Trim())

                'Recorre los items y los va actualizando
                Dim idCont As Integer = 0
                Dim fs As Double = 1
                Dim fs2 As Double = 1
                For i As Integer = 0 To Me.dtItems.Rows.Count - 1
                    If (CInt(Me.dtItems.Rows(i)("ID").ToString) < 400000) Then
                        idCont = CInt(Me.dtItems.Rows(i)("ID").ToString)
                    Else
                        idCont = 0
                    End If
                    fs = 1
                    fs2 = 1
                    If (Me.dtItems.Rows(i)("FS").ToString().Length > 0) Then
                        fs = CDbl(Me.dtItems.Rows(i)("FS").ToString())                    
                    End If
                    If (Me.dtItems.Rows(i)("FS2").ToString().Length > 0) Then
                        fs2 = CDbl(Me.dtItems.Rows(i)("FS2").ToString())                    
                    End If
                    Me.oGuia.ActualizarItemGuia(idCont, Me.idGuia, CDbl(Me.dtItems.Rows(i)("CANTIDAD").ToString), CDbl(Me.dtItems.Rows(i)("PESO").ToString), Me.dtItems.Rows(i)("UNIDAD").ToString, CDbl(Me.dtItems.Rows(i)("PESOCARGA").ToString), CDbl(Me.dtItems.Rows(i)("RATA").ToString), Me.dtItems.Rows(i)("PRODUCTO").ToString, fs, fs2)
                Next

                'Recorre los conceptos y los va actualizando
                Dim idCont2 As Integer = 0
                For i As Integer = 0 To Me.dtOtrosCargos.Rows.Count - 1
                    If (CInt(Me.dtOtrosCargos.Rows(i)("ID").ToString) < 400000) Then
                        idCont2 = CInt(Me.dtOtrosCargos.Rows(i)("ID").ToString)
                    Else
                        idCont2 = 0
                    End If
                    fs2 = 0
                    If (Me.dtOtrosCargos.Rows(i)("FS2").ToString().Length > 0) Then
                        fs2 = CDbl(Me.dtOtrosCargos.Rows(i)("FS2").ToString())
                    End If
                    Me.oGuia.ActualizarConceptoGuia(idCont2, CInt(Me.dtOtrosCargos.Rows(i)("IDCONCEPTO").ToString), Me.idGuia, CDbl(Me.dtOtrosCargos.Rows(i)("VALOR").ToString), CDbl(Me.dtOtrosCargos.Rows(i)("IVA").ToString), fs2)
                Next

                Cursor = Cursors.Default
                MessageBox.Show("La guía se guardó exitosamente", "", MessageBoxButtons.OK, MessageBoxIcon.Information)

                Me.CargarGrillaItems(True)
                Me.CargarGrillaConceptos(True)

                'Me.LimpiarTodo()
                'Me.TabControl1.SelectedTab = Me.tabListado                                
            Catch ex As Exception
                Cursor = Cursors.Default
                MessageBox.Show("No se guardó la guía: " & ex.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
            End Try
        End If
    End Sub

#Region "Impresion"

    Private Sub btnVisualizar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnVisualizar.Click
        If (Me.idGuia > 0) Then
            My.Forms.VerGuia.idGuia = Me.idGuia
            My.Forms.VerGuia.MdiParent = My.Forms.Principal
            My.Forms.VerGuia.Show()
        Else
            MessageBox.Show("Debe guardar esta guía para poderla imprimir", "", MessageBoxButtons.OK, MessageBoxIcon.Information)
        End If

    End Sub



#End Region





End Class